const path = require('path')
const { readFile, writeFile } = require('../fs/readFs')
const {ipcMain} = require('electron');

const { insertNewInfo, getTomatoData, deleteNewInfo, updateTaskEndCount } = require('./sqliteDB')

function initipcMain(dirname) {
    // 监听渲染进程发来的消息
    ipcMain.on('render-msg', async (event, arg) => {
        // if (typeof readFile == 'function') {
        //   event.sender.send('tomato-list', '方法存在')
        // }
        
        if (arg == '获取番茄钟') {
            // 通过json文件获取
            // let con = await readFile(path.join(dirname, './public/static/tomato.json') ).then(r=>r).catch(err=>err)
            // console.log(con)
            //  event.sender.send('tomato-list', con)
            // 通过数据库获取
            let res = await getTomatoData();
            event.sender.send('tomato-list', res)

        } else if (arg == '获取闹钟') {
            let con = await readFile(path.join(dirname, './public/static/clock.json') ).then(r=>r).catch(err=>err)
            event.sender.send('remind-list', con)
        }
    })
    
    // 保存数据
    ipcMain.on('save-msg', async (event, arg) => {
        let con = await writeFile(path.join(dirname, './public/static/tomato.json'), JSON.stringify(arg));
        // console.log(con)
        // event.sender.send('save-return', con)
    })
    
    ipcMain.on('save-remind-msg',async (event, arg) => {
         await writeFile(path.join(dirname, './public/static/clock.json'), JSON.stringify(arg));
        // console.log(con)
    })

    // 保存一条番茄钟新数据
    ipcMain.on('save-tomato-one-msg', async (event, arg) => {
        await insertNewInfo(arg);
    })
    // 删除一条番茄钟数据
    ipcMain.on('delete-tomato-one-msg', (event, arg) => {
        deleteNewInfo(arg);
    })
    // 修改番茄钟完成次数
    ipcMain.on('update-tomato-hasOk', (event, arg) => {
        updateTaskEndCount(arg)
    })

}

module.exports = { initipcMain }
